package com.xutianpeng.disk.register.control;

import com.xutianpeng.disk.user.exeption.MobileRepeatException;
import com.xutianpeng.disk.user.exeption.UserNameRepeatException;
import com.xutianpeng.disk.mybatis.entity.PtUserEntity;
import com.xutianpeng.disk.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Controller
@RequestMapping("/register")
public class RegisterController {

    private static final Logger logger = LoggerFactory.getLogger(RegisterController.class);

    @Resource
    private UserService userService;

    // 显示注册页面
    @RequestMapping
    public String registerPage() {
        return "register/registerPage";
    }

    // 发送验证码
    @RequestMapping("/sendCode")
    @ResponseBody
    public Map<String, Object> sendCode(@RequestParam String mobile, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 实际项目中应该调用短信服务API发送验证码
        String code = String.format("%06d", new Random().nextInt(999999));

        // 日志输出验证码（开发环境调试用）
        logger.info("【验证码调试】手机号: {}, 生成的验证码: {}", mobile, code);
        System.out.println("【验证码调试】手机号: " + mobile + ", 生成的验证码: " + code);

        // 将验证码存入session，有效期5分钟
        session.setAttribute("verifyCode_" + mobile, code);
        session.setMaxInactiveInterval(300);

        result.put("success", true);
        result.put("msg", "验证码已发送");
        // 临时返回验证码到前端（开发环境调试用，生产环境必须删除）
        result.put("debugCode", code);

        return result;
    }

    // 处理注册提交
    @RequestMapping("/submit")
    @ResponseBody
    public Map<String, Object> submitRegister(
            @RequestParam String mobile,
            @RequestParam String verifyCode,
            @RequestParam String username,
            @RequestParam String password,
            HttpSession session) {

        Map<String, Object> result = new HashMap<>();
        String storedCode = (String) session.getAttribute("verifyCode_" + mobile);

        // 验证码验证
        if (storedCode == null || !storedCode.equals(verifyCode)) {
            result.put("success", false);
            result.put("msg", "验证码错误或已过期");
            return result;
        }

        try {
            // 创建用户实体
            PtUserEntity user = new PtUserEntity();
            user.setUserUuid(UUID.randomUUID().toString()); // 生成唯一标识
            // 修复：将setUsername改为setUserName，与实体类方法名保持一致
            user.setUserName(username);
            user.setPassword(password); // 密码加密在UserService中处理
            user.setMobile(mobile);
            user.setRegisterdate(new java.sql.Timestamp(System.currentTimeMillis()).toString()); // 设置注册时间
            // 可根据实际需求添加其他默认字段（如状态、角色等）

            // 调用用户服务保存注册信息
            userService.addUserInfo(user);

            logger.info("用户注册成功，用户名: {}", username);
            result.put("success", true);
            result.put("msg", "注册成功，请登录");

        } catch (UserNameRepeatException e) {
            result.put("success", false);
            result.put("msg", "用户名已存在");
        } catch (MobileRepeatException e) {
            result.put("success", false);
            result.put("msg", "手机号已被注册");
        } catch (Exception e) {
            logger.error("注册失败", e);
            result.put("success", false);
            result.put("msg", "注册失败，请稍后重试");
        }

        return result;
    }
}